from flask import Flask, request, session, redirect, render_template
from markupsafe import Markup
import os
from .views.login import lg
from .views.help import hp
from .views.history import hy
from .views.feedback import fd
from .views.optimize import oe
from .views.setting import sg
from .views.register import rg
from .views.logout import lu


def current_user():
    user_dict = session.get("user_info")
    return user_dict["username"]


def auth():
    # 不需要登录即可访问的路径列表
    open_paths = ['/login', '/register', '/static']
    # 检查请求的路径是否在 open_paths 列表中
    if request.path.startswith(tuple(open_paths)):
        return  # 允许访问这些路径
    user_dict = session.get("user_info")
    if not user_dict:
        return redirect("/login")


def pager():
    current_page = request.args.get("page", "1")
    current_page = int(current_page)
    if current_page <= 1:
        prev_page = 1
    else:
        prev_page = current_page - 1
    next_page = current_page + 1
    boby = '''
    <ul class="pager">
        <li><a href="?page={}">上一页</a></li>
        <li><a href="?page={}">下一页</a></li>
    </ul>
    '''.format(prev_page, next_page)
    return Markup(boby)


def create_app():
    app = Flask(__name__)
    app.secret_key = 'asdasdasdasdasdasdasd'
    app.config['UPLOAD_FOLDER'] = os.path.join(app.root_path, "uploads")
    app.config['ALLOWED_EXTENSIONS'] = {'txt', 'csv', 'json'}  # 允许上传的文件类型
    app.config['DEFAULT_POPULATION_SIZE'] = 1000
    app.config['DEFAULT_N_GENERATIONS'] = 100
    app.config['DEFAULT_MAX_CAPACITY'] = 100
    app.config['DEFAULT_MUTATION_RATE'] = 0.5
    app.before_request(auth)
    app.template_global()(current_user)
    app.template_global()(pager)
    app.register_blueprint(lg)
    app.register_blueprint(hp)
    app.register_blueprint(hy)
    app.register_blueprint(fd)
    app.register_blueprint(oe)
    app.register_blueprint(sg)
    app.register_blueprint(rg)
    app.register_blueprint(lu)

    return app
